<template>
	<view class="buy-course-container">
		<uv-toast ref="toast"></uv-toast>
		<skeleton-card-list :loading="loading" type="course" :count="1">
			<!-- 当数据加载完成时才显示内容 -->
			<template v-if="courseDetail.id">
				<!-- 顶部课程信息卡片 -->
				<view class="course-card">
					<image class="course-cover" :src="courseDetail.image" mode="aspectFill"></image>
					<view class="course-info">
						<text class="course-title">{{ courseDetail.name }}</text>
						<view class="course-stats">
							<!-- <view class="stat-item">
								<text class="iconfont icon-user"></text>
								<text>{{ courseInfo.studentCount }}人已学习</text>
							</view> -->
							<view class="stat-item">
								<text class="iconfont icon-time"></text>
								<text>{{ medias.length}}课时</text>
							</view>
						</view>
						<view class="price-box">
							<text class="current-price">¥{{ courseDetail.price }}</text>
							<text class="original-price">¥{{ courseDetail.originalPrice }}</text>
							<text class="discount-tag">限时优惠</text>
						</view>
					</view>
				</view>

				<!-- 课程介绍 -->
				<view class="course-intro-section">
					<view class="section-title">
						<text class="title-text">课程介绍</text>
					</view>
					<view class="intro-content">
						<text class="intro-text">{{ courseDetail.description}}</text>
						<view class="intro-tags">
							<text class="tag-item" v-for="(tag, index) in parseTagList(courseDetail.tags)" :key="index">
								{{ tag }}
							</text>
						</view>
					</view>
				</view>

				<!-- 课程目录 -->
				<view class="chapters-section">
					<view class="section-title">
						<text class="title-text">课程目录</text>
						<text class="chapter-stats">共{{ medias.length }}集 · {{ totalDuration }}</text>
					</view>
					<view class="chapter-list">
						<view class="lesson-item" v-for="(media, index) in medias" :key="media.id"
							@tap="handlePlayVideo(media)">
							<view class="lesson-left">
								<text class="lesson-index">{{ index + 1 }}</text>
								<image class="lesson-cover" :src="media.coverImageUrl" mode="aspectFill">
								</image>
								<view class="lesson-info">
									<text class="lesson-title">{{ media.title }}</text>
									<text class="lesson-desc">{{ media.des || '暂无简介' }}</text>
								</view>
							</view>
							<text class="lesson-duration">{{ formatDuration(media.duration) }}</text>
						</view>
					</view>
				</view>

				<!-- 底部购买栏 -->
				<view class="bottom-bar">
					<view class="price-info">
						<text class="current-price">¥{{ courseDetail.price }}</text>
						<text class="original-price">¥{{ courseDetail.originalPrice }}</text>
					</view>
					<button class="buy-btn" @tap="handleBuy">{{ isBuy ? '立即观看' : '立即购买'}}</button>
				</view>
			</template>
		</skeleton-card-list>
	</view>
</template>

<script>
	import {
		isUserLoggedIn,
		isMerchantLoggedIn
	} from '@/plugins/auth.js';
	import SkeletonCardList from '@/components/common/skeleton-card-list/skeleton-card-list.vue'

	export default {
		components: {
			SkeletonCardList
		},
		data() {
			return {
				medias: [],
				mediasPagenation: {
					total: 0,
					current: 1,
					pageSize: 100,
				},
				courseDetail: {},
				totalDuration: '00:00:00',
				loading: false,
				isBuy: false,
			}
		},

		onLoad(options) {
			if (options.courseId) {
				this.courseId = options.courseId;
				this.initData();
			} else {
				this.showToast('课程不存在');
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		},

		methods: {
			showToast(msg, type = 'default', duration = 1000) {
				this.$refs.toast.show({
					message: msg,
					type: type,
					duration: duration,
				})
			},
			// 购买逻辑
			handleBuy() {
				if (!isUserLoggedIn()) {
					this.showToast('请先登录');
					return;
				} else {
					if (isMerchantLoggedIn() && !isUserLoggedIn()) {
						this.showToast('请先登录用户端');
						return;
					}
				}
				if (!this.isBuy) {
					uni.navigateTo({
						url: `/subpkg/buy_course/buy_course?courseId=${this.courseId}`
					})
				} else {
					if (this.medias.length === 0) {
						this.showToast('暂无可播放课程');
						return;
					}
					// 跳转到第一集播放
					uni.navigateTo({
						url: `/subpkg/video_pay_course_play/video_pay_course_play?courseId=${this.medias[0].courseId}&courseMediaId=${this.medias[0].id}`
					})
				}
			},
			// 解析标签字符串为数组
			parseTagList(tags) {
				return tags ? tags.split(',').filter(tag => tag.trim()) : [];
			},
			// 格式化视频时长
			formatDuration(seconds) {
				if (!seconds) return '00:00';
				// 将字符串转为数字
				seconds = Number(seconds);
				const h = Math.floor(seconds / 3600);
				const m = Math.floor((seconds % 3600) / 60);
				const s = Math.floor(seconds % 60);

				if (h > 0) {
					return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
				}
				return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
			},

			// 计算总时长
			calculateTotalDuration() {
				const totalSeconds = this.medias.reduce((total, media) => {
					return total + (Number(media.duration) || 0);
				}, 0);
				this.totalDuration = this.formatDuration(totalSeconds);
			},
			async fetchBatchVideoInfos() {
				try {
					this.loading = true;
					const videoIds = this.medias.map(item => item.videoId).join(',');

					// 如果没有videoIds则直接返回
					if (!videoIds) return;

					const data = await this.$http.post(`/courses/media/batch/video/infos?videoIds=${videoIds}`);

					if (data && Array.isArray(data)) {
						// 将点播信息数据转换为以videoId为key的映射对象，方便查找
						const videoInfoMap = data.reduce((map, item) => {
							map[item.videoId] = item;
							return map;
						}, {});

						// 更新medias数组，添加coverUrl和duration字段
						this.medias = this.medias.map(media => {
							const videoInfo = videoInfoMap[media.videoId] || {};

							return {
								...media,
								coverImageUrl: media.coverImageUrl || videoInfo.coverURL, // 如果没有新的封面则使用原封面
								duration: videoInfo.duration || 0
							};
						});
					}
					this.calculateTotalDuration();
				} catch (e) {
					this.showToast(e.msg || '获取点播信息失败');
				} finally {
					this.loading = false;
				}
			},
			async fetchCourseMedia() {
				try {
					this.loading = true;
					const obj = {
						...this.mediasPagenation,
						courseId: this.courseId
					};
					const data = await this.$http.post('/courses/media/list', obj);

					if (data) {
						this.mediasPagenation.total = data.count;
						this.mediasPagenation.current += 1;
						this.medias = data.items;
					}

					await this.fetchBatchVideoInfos();
				} catch (e) {
					this.showToast(e.msg || '获取课程详情失败');
				} finally {
					this.loading = false;
				}
			},
			async fetchCourseDetail() {
				try {
					this.loading = true;

					const res = await this.$http.get(`/course/info?courseId=${this.courseId}`);

					if (res) {
						this.courseDetail = {
							...this.courseDetail,
							...res
						};
					} else {
						throw new Error(res.msg || '获取课程详情失败');
					}
				} catch (e) {
					console.error('获取课程详情失败:', e);
					this.showToast(e.msg || '获取课程详情失败');
				} finally {
					this.loading = false;
				}
			},
			handlePlayVideo(media) {
				if (this.isBuy) {
					uni.navigateTo({
						url: `/subpkg/video_pay_course_play/video_pay_course_play?courseId=${media.courseId}&courseMediaId=${media.id}`
					})
					return;
				}
			},
			async fetchCourseOrder() {
				try {
					const data = await this.$http.post(`/order/course?courseId=${this.courseId}`);
					if (data && data >= 1) {
						this.isBuy = true;
					}
				} catch (e) {
					console.error('获取用户课程订单失败', e);
					this.showToast(`加载失败`);
					setTimeout(() => {
						uni.navigateBack();
					});
				}
			},
			// 初始化数据
			async initData() {
				this.loading = true;
				try {
					await Promise.all([
						this.fetchCourseDetail(),
						this.fetchCourseMedia(),
						this.fetchCourseOrder()
					]);
				} catch (e) {
					console.error('初始化数据失败:', e);
				} finally {
					this.loading = false;
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import 'course_detail.scss';
</style>